<template>
  <div>
    <el-upload
      :ref="refName"
      :action="uploadUrl"
      with-credentials
      :data="uploadData"
      :headers="headers"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-change="changeUploadFiles"
      :auto-upload="isAutoUpload"
      :disabled="isDisabled"
      :limit="limitNumber"
      :accept="acceptFormat"
      :on-exceed="numberExceeded"
      :multiple="limitNumber && limitNumber > 1 ? true : false"
      :show-file-list="false"
    >
      <!--:file-list="files"-->
      <!--:name="fileKey.key||'file_name'"-->
      <el-button
        slot="trigger"
        size="small"
        type="primary"
        :disabled="isDisabled"
      >选取文件
      </el-button>
      <div v-if="fileList.length > 0 && isCustomShow">
        <div v-for="(file, index) in fileList" :key="index"
             class="custom-file-list">
          <span @click="downloadCurFile(file,index)">
            {{ file.name }}
            <i class="el-icon-close" @click="delCurFile(file, index)"
               v-if="!isDisabled"></i>
          </span>
        </div>
      </div>
      <!--<el-button style="margin-left: 10px;" size="small" type="success"
                 @click="submitUpload">上传到服务器
      </el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
    </el-upload>
  </div>
</template>

<script>
/**
 * @Description:  完整性校验的upload组件 示例
 */
// import {getItem} from "@/utils/safeSettings/auth";
import {Message} from "element-ui";
// import URL_CONFIG from "@/api/zhjz/config";

export default {
  name: "upload-safe",
  props: {
    fileKey: {
      type: String | Object | null,
      default() {
        return null; // 此值主要在于记录的修改的哪一个的file upload值，可不填写
      },
    },
    uploadUrl: {
      type: String,
      default() {
        return '/file/upload'
        // return 'http://192.168.55.155:51021/dev-api/zhjzsxj/wenjian/shangchuan'
        // return 'dev-api/zhjzsxj/file/upload'
        // return 'dev-api/zhjzsxj/wenjian/shangchuan'
        // return (
        //   process.env.VUE_APP_BASE_API +
        //   URL_CONFIG.proUrl +
        //   "/file/upload"
        // ).substr(1);
      },
    },
    refName: {
      type: String,
      default() {
        return "upload";
      },
    },
    dataObj: {
      type: Object | null,
      default() {
        return null;
      },
    },
    isDisabled: {
      type: Boolean,
      default() {
        return false;
      },
    },
    isCustomShow: {
      type: Boolean,
      default() {
        return true;
      },
    },
    isAutoUpload: {
      type: Boolean,
      default() {
        return true;
      },
    },
    isSubmitUpload: {
      type: Boolean,
      default() {
        return false; // 此参数只有在isAutoUpload时有效
      },
    },
    fileList: {
      type: Array,
      default() {
        return [];
      },
    },
    acceptFormat: {
      type: String,
      default() {
        return ""; // .png,.jpg,.jpeg
      },
    },
    formatTypeList: {
      type: Array,
      default() {
        return []; // 空时不判断，非空时判断
      },
    },
    limitNumber: {
      type: Number,
      default() {
        return 999; // .png,.jpg,.jpeg
      },
    },
    isClearFiles: {
      type: Boolean,
      default() {
        return false;
      },
    },
  },
  watch: {
    dataObj: {
      handler(val, oldVal) {
        if (val && typeof val == "object") {
          this.uploadData = Object.assign(this.uploadData, val);
        }
      },
      immediate: true,
      deep: true,
    },
    fileList: {
      handler(val, oldVal) {
        if (val) {
          this.files = val || [];
        }
      },
      immediate: true,
      deep: true,
    },
    isSubmitUpload: {
      handler(val, oldVal) {
        if (val) {
          this.$refs[this.refName].submit();
          this.$emit("changeIsSubmitUpload", false);
        }
      },
      immediate: true,
      deep: true,
    },
    isClearFiles: {
      handler(val, oldVal) {
        if (val) {
          this.$refs[this.refName].clearFiles();
          this.$emit("changeIsClearFiles", false);
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      fileChangeNum: 0,
      initFiles: [],
      files: [],
      // name: 'f', //文件名
      headers: {},
      uploadData: {
        // name:'2s'
      },
    };
  },
  created() {
    this.$set(this.uploadData, "user", this.$store.getters.user.userId);
  },
  methods: {
    //c: rsa('file')
    //d:md5  (uid +(name , contentType ,size))
    handleUrl(url) {
      url = url || "";
      url = url.split(" ").join("");
      const arr = url.split("/");
      let tempArr = [];

      arr.forEach((u) => {
        if (u !== "") {
          tempArr.push(u);
        }
      });
      tempArr.unshift("");

      return tempArr.join("/");
    },
    generateData(params) {
      const keys = Object.keys(params);
      const desKeys = keys.sort().reverse();
      let data = [];
      desKeys.forEach((item) => {
        data.push(params[item]);
      });

      return data.join(",");
    },
    delCurFile(file, index) {
      this.files.splice(index, 1);
      this.$emit("updateFileList", {
        fileKey: this.fileKey,
        file: file,
        fileList: this.files,
        resData: null,
      });
    },
    downloadCurFile(file, index) {
      if (this.isDisabled && file.url) {
        window.open(file.url)
      }
    },
    handleRemove(file, fileList) {
      console.log("remove=======", file, fileList);
      // this.$emit("updateFileList", {
      //   fileKey: this.fileKey,
      //   file: file,
      //   fileList: fileList,
      //   resData: null,
      // });
    },
    handlePreview(file) {
      // console.log('preview 000000000000')
    },
    changeUploadFiles(file, fileList) {
      // console.log("change=======", file, fileList);
      // const token = "Bearer" + getItem("Authorization");
      // this.headers = this.$request.initUploadHeaders(
      //   file,
      //   this.uid(),
      //   this.stime(),
      //   token,
      //   this.action
      // );
    },
    beforeUpload(file) {
      // const token = "Bearer" + getItem("Authorization");
      // this.headers = this.$request.initUploadHeaders(
      //   file,
      //   this.uid(),
      //   this.stime(),
      //   token,
      //   this.action
      // );
      let fileNameArr = file.name ? file.name.split('.') : [];
      let houzhui = fileNameArr.length > 0 ? fileNameArr[fileNameArr.length
      - 1] : '';

      let isFormat = true;
      if (this.formatTypeList.length > 0) {
        isFormat = this.formatTypeList.includes(file.type);
        if (!isFormat) {
          Message.warning("上传文件不符合要求的格式!");
        }
      }
      let acceptFormatArr = this.acceptFormat ? this.acceptFormat.split(',')
        : [];
      console.log(houzhui, JSON.stringify(acceptFormatArr))
      if (acceptFormatArr.length > 0) {
        isFormat = acceptFormatArr.indexOf('.' + houzhui) > -1;
        console.log(isFormat)
        if (!isFormat) {
          Message.warning("上传文件不符合要求的格式!");
        }
      }

      // let isLimit = file.size / 1024 / 1024 < 10;
      // if (!isLimit){
      //   Message.warning("上传文件大小不能超过 10MB!");
      // }
      // if ()
      return isFormat;
      // },800);
    },
    handleSuccess(res, file, fileList) {
      // console.log('success 33333333333',this.headers)
      // console.log("~~~~~~~~~~", JSON.stringify(fileList));
      //成功之后清空数据
      // this.fileList = [];
      if (res.result == 0) {
        // let resList = [];
        // for (let i = 0; i < fileList.length; i++) {
        //   let tp = fileList[i];
        //   let todoItem =
        //     tp && tp.response && tp.response.data ? tp.response.data : null;
        //   if (todoItem) {
        //     Object.assign(todoItem, {
        //       name: todoItem.org_name || todoItem.name || "",
        //     });
        //   } else {
        //     continue;
        //   }
        //   resList.push(todoItem);
        // }
        let todoItem =
          file && file.response && file.response.data
            ? file.response.data
            : null;
        let curFileObj = todoItem;
        if (todoItem) {
          curFileObj = Object.assign(todoItem, {
            name: todoItem.org_name || todoItem.name || "",
          });
        }

        // console.log(curFileObj);

        let resList = this.files.slice();
        if (curFileObj) {
          resList.push(curFileObj);
        }
        // console.log(resList);

        if (!res.data || res.data.fail == undefined) {
          // let resData = res.data;
          // Object.assign(resData, {
          //   name: resData.org_name || resData.name || '',
          // });
          this.$emit("updateFileList", {
            fileKey: this.fileKey,
            file: file,
            fileList: resList,
            resData: res.data || null,
          });
        } else {
          if (res.data.fail == 0) {
            Message.success(res.data.success + "条数据导入成功");
          } else {
            let line = res.data.fail_array.join(",");
            /* Message.error(
               "数据导入有" +
               res.data.fail +
               "条错误，在" +
               line +
               "行数据有误！"
             );*/
            //错误信息不自动关闭
            this.$message({
              showClose: true,
              message:
                "数据导入有" +
                res.data.fail +
                "条错误，在" +
                line +
                "行数据有误！",
              type: "error",
              duration: 0,
            });
          }
          this.$emit("updateFileList", {
            fileKey: this.fileKey,
            file: file,
            fileList: resList,
            resData: res.data || null,
          });
        }
      } else {
        this.fileChangeNum = 0;
        this.$emit("updateFileListErr", {});
        Message.error(res.msg || res.message || "上传失败！");
      }
    },
    //文件超出一个
    numberExceeded() {
      Message.warning("文件上传超出限制数量了！");
    },
  },
};
</script>

<style scoped>
.custom-file-list {
  white-space: pre-line;
  /* padding: 8px 0; */
  line-height: 28px;
}

.custom-file-list > span:hover {
  background-color: rgba(0, 0, 0, 0.1);
}

.custom-file-list > span .el-icon-close {
  margin-left: 4px;
}
</style>
